package com.zjl.media.config;

import com.zjl.media.config.properties.MediaProperties;
import com.zjl.media.core.MediaManager;
import com.zjl.media.netty.FlvHandler;
import com.zjl.media.netty.MediaServerInitializer;
import com.zjl.media.netty.NettyServer;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author linfuxin Created on 2022-03-01 15:45:24
 */
@Configuration
@EnableConfigurationProperties(MediaProperties.class)
@EnableScheduling
public class MediaConfig {

    @Bean
    public MediaManager mediaManager(MediaProperties mediaProperties) {
        ThreadFactory threadFactory = new ThreadFactory() {
            final AtomicInteger tag = new AtomicInteger(0);

            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("推流线程-" + tag.incrementAndGet());
                return thread;
            }
        };
        ExecutorService executorService = new ThreadPoolExecutor(8, 8, 30, TimeUnit.SECONDS, new LinkedBlockingDeque<>(20), threadFactory);
        return new MediaManager(executorService, mediaProperties);
    }

    @Bean
    public FlvHandler flvHandler(MediaManager mediaManager,MediaProperties mediaProperties) {
        return new FlvHandler(mediaManager, mediaProperties);
    }

    @Bean
    public MediaServerInitializer nettyServerInitializer(FlvHandler flvHandler) {
        return new MediaServerInitializer(flvHandler);
    }

    @Bean
    public NettyServer mediaServer(MediaProperties webSocketProperties, MediaServerInitializer nettyServerInitializer) {
        return new NettyServer(webSocketProperties, nettyServerInitializer);
    }
}
